<?php
defined('_JEXEC') or die('Restricted access');

class User_Model extends Model {

/**
 * Database tablename: tbl_users
 * cols:
 *   id               bigint(20)   PrimaryKey
 *   username         varchar(255) Index, Unique
 *   password         varchar(255)
 *   email_address    varchar(255) Index, Unique
 *   date_created     datetime
 *   date_last_access datetime
 *   status           int(10)      Index, Default 1, foreign key: tbl_users_status -> id 
 * 
 * 
 */
    public function __construct() {
        parent::__construct(__CLASS__, "user");
    }

    public function usernameExists($username) {
        return parent::recordExists("username", $username);
    }

    public function emailExists($email) {
        return parent::recordExists("email", $email);
    }

    public function userList() {
        return parent::getAll_Records();
    }

    public function userSingleList($id) {
        return parent::getSingleRecord_By("id", $id);
    }

    public function getAllUsernames() {
        return parent::getAllRecords_By("username");
    }

    public function getAllEmails() {
        return parent::getAllRecords_By("email");
    }

    public function findUser_byUsername($username) {
        return parent::getSingleRecord_By("username", $username);
    }

    public function findUser_byEmail($email) {
        return parent::getSingleRecord_By("email", $email);
    }

    public function createNewUser($data) {
        return parent::create($data);
    }

    public function assignUserTo_aGroup_byID($user_id, $group_id) {
        $usr_grp_m = new User_group_Model();
        $r = $usr_grp_m->_db->select("SELECT * FROM `$usr_grp_m->_tableName` WHERE `user_id` = :uid AND `group_id` = :gid LIMIT 1", array(':uid'=>$user_id, ':gid'=>$group_id));
        
         // if record already exists, just return
        if (count($r)>0){
            return -1;
        }
        
        $d = array(
            'user_id' => $user_id,
            'group_id' => $group_id,
            'description' => "",
            'date_created' => date("Y-m-d H:i:s", time()), //date-time formated as MySQL DATETIME
        );
        return $usr_grp_m->create($d);
    }

    public function removeUserFrom_aGroup_byID($user_id, $group_id) {
        
    }

    public function editSave($data) {
        $postData = array(
            'login' => $data['login'],
            'password' => Hash::create('sha256', $data['password'], HASH_PASSWORD_KEY),
            'role' => $data['role']
        );

        return parent::update($postData, "`id` = {$data['id']}");
    }

    /**
     *
     * @param integer $id The id of the user to delete 
     */
    public function delete($id) {
        return $this->delete_SingleRecord("`id` = ".$id);
    }

}